/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import entities.KeyWord;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Problem;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author santiagobaldrich
 */
public class KeyWordJpaController {

    public KeyWordJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(KeyWord keyWord)
    {
        if (keyWord.getProblemCollection() == null)
        {
            keyWord.setProblemCollection(new ArrayList<Problem>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Problem> attachedProblemCollection = new ArrayList<Problem>();
            for (Problem problemCollectionProblemToAttach : keyWord.getProblemCollection())
            {
                problemCollectionProblemToAttach = em.getReference(problemCollectionProblemToAttach.getClass(), problemCollectionProblemToAttach.getIdProblem());
                attachedProblemCollection.add(problemCollectionProblemToAttach);
            }
            keyWord.setProblemCollection(attachedProblemCollection);
            em.persist(keyWord);
            for (Problem problemCollectionProblem : keyWord.getProblemCollection())
            {
                problemCollectionProblem.getKeyWordCollection().add(keyWord);
                problemCollectionProblem = em.merge(problemCollectionProblem);
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(KeyWord keyWord) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            KeyWord persistentKeyWord = em.find(KeyWord.class, keyWord.getIdKeyWord());
            Collection<Problem> problemCollectionOld = persistentKeyWord.getProblemCollection();
            Collection<Problem> problemCollectionNew = keyWord.getProblemCollection();
            Collection<Problem> attachedProblemCollectionNew = new ArrayList<Problem>();
            for (Problem problemCollectionNewProblemToAttach : problemCollectionNew)
            {
                problemCollectionNewProblemToAttach = em.getReference(problemCollectionNewProblemToAttach.getClass(), problemCollectionNewProblemToAttach.getIdProblem());
                attachedProblemCollectionNew.add(problemCollectionNewProblemToAttach);
            }
            problemCollectionNew = attachedProblemCollectionNew;
            keyWord.setProblemCollection(problemCollectionNew);
            keyWord = em.merge(keyWord);
            for (Problem problemCollectionOldProblem : problemCollectionOld)
            {
                if (!problemCollectionNew.contains(problemCollectionOldProblem))
                {
                    problemCollectionOldProblem.getKeyWordCollection().remove(keyWord);
                    problemCollectionOldProblem = em.merge(problemCollectionOldProblem);
                }
            }
            for (Problem problemCollectionNewProblem : problemCollectionNew)
            {
                if (!problemCollectionOld.contains(problemCollectionNewProblem))
                {
                    problemCollectionNewProblem.getKeyWordCollection().add(keyWord);
                    problemCollectionNewProblem = em.merge(problemCollectionNewProblem);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = keyWord.getIdKeyWord();
                if (findKeyWord(id) == null)
                {
                    throw new NonexistentEntityException("The keyWord with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            KeyWord keyWord;
            try
            {
                keyWord = em.getReference(KeyWord.class, id);
                keyWord.getIdKeyWord();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The keyWord with id " + id + " no longer exists.", enfe);
            }
            Collection<Problem> problemCollection = keyWord.getProblemCollection();
            for (Problem problemCollectionProblem : problemCollection)
            {
                problemCollectionProblem.getKeyWordCollection().remove(keyWord);
                problemCollectionProblem = em.merge(problemCollectionProblem);
            }
            em.remove(keyWord);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<KeyWord> findKeyWordEntities()
    {
        return findKeyWordEntities(true, -1, -1);
    }

    public List<KeyWord> findKeyWordEntities(int maxResults, int firstResult)
    {
        return findKeyWordEntities(false, maxResults, firstResult);
    }

    private List<KeyWord> findKeyWordEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(KeyWord.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public KeyWord findKeyWord(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(KeyWord.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getKeyWordCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<KeyWord> rt = cq.from(KeyWord.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public KeyWord getKeyWordByName(String name)
    {
        EntityManager em = null;
        KeyWord k = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("KeyWord.findByName");
            q.setParameter("name", name);
            k = (KeyWord) q.getSingleResult();
        } catch (Exception e)
        {
            k = null;
        } finally
        {
            em.close();
            return k;
        }
    }

    public List<KeyWord> findAll()
    {
        EntityManager em = getEntityManager();
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("KeyWord.findAll");
            return (List<KeyWord>)q.getResultList();
        } catch (Exception e)
        {
            return null;
        }
    }
}
